#include<iostream>

#include<stdio.h>

#include<string.h>

#include <stdlib.h>

#include<unistd.h>

#include <sys/wait.h>

#define PATH_MAX 1024

#define INPUT_MAX 1024

using namespace std;

void print_menu()
{
  char arr_cwd[PATH_MAX];
  getcwd(arr_cwd, PATH_MAX);
  char* pm_token = strtok(arr_cwd, "/");
  char* prev_pm_token = NULL;
  char tmp[] = "/";
  while(pm_token)
  {
    prev_pm_token = pm_token;
    pm_token = strtok(NULL,"/");
  }
  if(!prev_pm_token) prev_pm_token = tmp;
  cout << "mybash:[" << getenv("USER") << "@" << getenv("HOSTNAME") << " " << prev_pm_token << "]" 
    << (strcmp(getenv("USER"), "root")? "$ " : "# ");
}

int my_cd(const char* str)
{
  char arr[INPUT_MAX] = {'P', 'W', 'D', '='};
  for(int i = 0; str[i]; ++i)
  {
    arr[i + 4] = str[i];
  }
  cout << arr << endl;
  cout << str << endl;
  putenv(arr);
  return chdir(str);
}

int main()
{
  while(1)
  {
    print_menu();
    char arr_input[INPUT_MAX] = {0};
    fgets(arr_input, INPUT_MAX, stdin);
    size_t len = strlen(arr_input);
    if(len > 0 && arr_input[len-1] == '\n')
    {
      arr_input[len-1] = '\0';
    }
    char* token = strtok(arr_input, " ");
    char* ARGV[INPUT_MAX] = {0};
    int i = 0;
    int num = 0;
    while(token)
    {
      ARGV[i++] = token;
      ++num;
      token = strtok(NULL, " ");
    }
    if(strcmp(ARGV[0], "cd") == 0 && num == 2)
    {
      my_cd(ARGV[1]);
    }
    else
    {
      int ret = fork();
      if(ret == 0)
      {
        execvp(ARGV[0], ARGV);
      }
      else if(ret > 0)
      {
        int st = 0;
        wait(&st);
        if(WIFEXITED(st))
        {
          if(WEXITSTATUS(st)) cout << strerror(WEXITSTATUS(st)) << endl;
        }
        else
        {
          cout << strsignal(WTERMSIG(st)) << endl;
        }
      }
    }
  }
  return 0;
}
